<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Router Class
 *
 * Parses URIs and determines routing
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @author		ExpressionEngine Dev Team
 * @category	Libraries
 * @link		http://codeigniter.com/user_guide/general/routing.html
*/
class Router {

	/**
	 * List of routes
	 *
	 * @var array
	 * @access public
	 */
	var $routes			= array();

	var $args			= array();
	var $skips			= array();
	/**
	 * List of error routes
	 *
	 * @var array
	 * @access public
	*/
	var $error_routes	= array();
	/**
	 * Current class name
	 *
	 * @var string
	 * @access public
	*/
	var $class			= '';
	/**
	 * Current method name
	 *
	 * @var string
	 * @access public
	 */
	var $method			= 'index';
	/**
	 * Sub-directory that contains the requested controller class
	 *
	 * @var string
	 * @access public
	 */
	var $directory		= '';
	/**
	 * Default controller (and method if specific)
	 *
	 * @var string
	 * @access public
	 */
	var $default_module;

	/**
	 * Constructor
	 *
	 * Runs the route mapping function.
	 */
	function __construct()
	{
		$this->uri =& load_class('URI', 'core');
	}

	// --------------------------------------------------------------------

	/**
	 * Set the route mapping
	 *
	 * This function determines what should be served based on the URI request,
	 * as well as any "routes" that have been set in the routing config file.
	 *
	 * @access	private
	 * @return	void
	 */
	function _set_routing()
	{
		// Are query strings enabled in the config file?  Normally CI doesn't utilize query strings
		// since URI segments are more search-engine friendly, but they can optionally be used.
		// If this feature is enabled, we will gather the directory/class/method a little differently
		$segments = array();
		if (config_item('enable_query_strings') AND isset($_GET[config_item('module_trigger')])){
			if (isset($_GET[config_item('module_trigger')])){
				$this->set_directory(trim($this->uri->_filter_uri($_GET[config_item('module_trigger')])));
				$segments[] = $this->fetch_directory();
				$this->set_class($segments[0]);
			}
				
			if (isset($_GET[config_item('function_trigger')])){
				$this->set_method(trim($this->uri->_filter_uri($_GET[config_item('function_trigger')])));
				$segments[] = $this->fetch_method();
			}
		}

		if (is_file(APPPATH.'config/routes.php')){
			include(APPPATH.'config/routes.php');
		}

		$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
		unset($route);

		$this->args = ( ! isset($arg) OR ! is_array($arg)) ? array() : $arg;
		unset($arg);

		$this->skips = ( ! isset($skip) OR ! is_array($skip)) ? array() : $skip;
		unset($skip);
		// Set the default controller so we can display it in the event
		// the URI doesn't correlated to a valid controller.
		$dm = config_item('default_module');
		$this->default_module = ( ! isset($dm) OR $dm == '') ? FALSE : strtolower($dm);

		// Were there any query string segments?  If so, we'll validate them and bail out since we're done.
		if (count($segments) > 0){
			return $this->_validate_request($segments);
		}

		// Fetch the complete URI string
		$this->uri->_fetch_uri_string();

		// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
		if ($this->uri->uri_string == ''){
			return $this->_set_default_module();
		}

		// Do we need to remove the URL suffix?
		$this->uri->_remove_url_suffix();

		// Compile the segments into an array
		$this->uri->_explode_segments();

		// Parse any custom routing that may exist
		$this->_parse_routes();

		// Re-index the segment array so that it starts with 1 rather than 0
		$this->uri->_reindex_segments();
	}

	// --------------------------------------------------------------------

	/**
	 * Set the default controller
	 *
	 * @access	private
	 * @return	void
	 */
	function _set_default_module()
	{
		if ($this->default_module === FALSE){
			show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
		}
		// Is the method being specified?
		if (strpos($this->default_module, '/') !== FALSE){
			$x = explode('/', $this->default_module);
			$this->set_directory($x[0]);
			$this->set_class($x[0]);
			$this->set_method($x[1]);
			$this->_set_request($x);
		}else{
			$this->set_class($this->default_module);
			$this->set_method('index');
			$this->_set_request(array($this->default_module, 'index'));
		}

		// re-index the routed segments array so it starts with 1 rather than 0
		$this->uri->_reindex_segments();

	}

	// --------------------------------------------------------------------

	/**
	 * Set the Route
	 *
	 * This function takes an array of URI segments as
	 * input, and sets the current class/method
	 *
	 * @access	private
	 * @param	array
	 * @param	bool
	 * @return	void
	 */
	function _set_request($segments = array()){
		$segments = $this->_validate_request($segments);

		if (count($segments) == 0){
			return $this->_set_default_module();
		}

		$this->set_directory($segments[0]);
		$this->set_class($segments[0]);

		if (isset($segments[1])){
			$tempseg = explode('?', $segments[1]);
			if(count($tempseg)>1){
				$segments[1] = $tempseg[0];
			}
			// A standard method request
			$this->set_method($segments[1]);
		}else{
			// This lets the "routed" segment array identify that the default
			// index method is being used.
			$segments[1] = 'index';
		}

		// Update our "routed" segment array to contain the segments.
		// Note: If there is no custom routing, this array will be
		// identical to $this->uri->segments
		$this->uri->rsegments = $segments;
	}

	// --------------------------------------------------------------------

	/**
	 * Validates the supplied segments.  Attempts to determine the path to
	 * the controller.
	 *
	 * @access	private
	 * @param	array
	 * @return	array
	 */
	function _validate_request($segments)
	{
		if (count($segments) == 0){
			return $segments;
		}
		// Does the requested controller exist in the root folder?
		if (file_exists(APPPATH.'modules/'.$segments[0].'/'.str_replace(array('/', '.'), '', $segments[0]).'_controller.php')){
			return $segments;
		}

		// If we've gotten this far it means that the URI does not correlate to a valid
		// controller class.  We will now see if there is an override
		if ( !empty($this->routes['404_override'])){
			$x = explode('/', $this->routes['404_override']);
			$this->set_directory($x[0]);
			$this->set_class($x[0]);
			$this->set_method(isset($x[1]) ? $x[1] : 'index');

			return $x;
		}

		// Nothing else to do at this point but show a 404
		show_404($segments[0]);
	}

	// --------------------------------------------------------------------

	function _scriptname(){
		if(isset($GLOBALS['SCRIPTNAME'])) return $GLOBALS['SCRIPTNAME'];
		$scriptname = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
		$scriptname = rtrim($scriptname, '/').'/';
		$GLOBALS['SCRIPTNAME'] = $scriptname;
		return $scriptname;
	}


	function _parse_uri($uri){
		//$uri = stripcslashes($uri);
		$uris = explode('?', $uri);
		$config['pathinfo_support'] = FALSE;
		$scriptname = $this->_scriptname();
		if(!config_item('pathinfo_support')){
			$loaders = explode(config_item('url_sep'), $uris[0]);
			$module = $loaders[0];
			$action = $loaders[1];
			$param = ($uris[1])?'&'.$uris[1]:'';
			//return base_url().config_item('index_page').'?'.config_item('module_trigger').'='.$module.'&'.config_item('function_trigger').'='.$action.$param;
			return $scriptname.config_item('index_page').'?'.config_item('module_trigger').'='.$module.'&'.config_item('function_trigger').'='.$action.$param;
		}

		//$base_url = config_item('url_rewrite')?base_url():base_url().config_item('index_page').'/';
		$base_url = config_item('url_rewrite')?$scriptname:$scriptname.config_item('index_page').'/';

		if($kk = $this->_check_route_reg($uri)){
			if(isset($uris[1]) AND isset($this->args[$kk])){
				parse_str($uris[1], $vars);
				$key = str_replace(':any', '[^&/]+', str_replace(':num', '[0-9]+', $kk));
				$argstr = $this->args[$kk];
				preg_match_all('/\((\w+)\)/', $argstr, $matches,PREG_SET_ORDER);
				if(count($matches)==count($vars)){
					foreach ($vars as $key=>$val){
						$argstr = preg_replace('/\('.$key.'\)/i', $val, $argstr);
					}
					return $base_url.str_replace(array('&','='), array('/','/'), stripcslashes($argstr)).config_item('url_suffix');
				}
			}else if(!isset($uris[1]) AND ($kk=='default_module')){
				return $base_url;
			}else if(!isset($uris[1]) AND !isset($this->args[$kk])){
				return $base_url.stripcslashes($kk).config_item('url_suffix');
			}else if(!isset($uris[1]) AND isset($this->args[$kk])){
				return $base_url.stripcslashes($uris[0]).config_item('url_suffix');
			}
		}
		/*
		 if($k = array_search(strtolower($uris[0]), array_map('strtolower',$this->routes))){
		if(isset($uris[1]) AND isset($this->args[$k])){
		parse_str($uris[1], $vars);
		$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $k));
		//preg_match('#^'.$key.'$#', $uri, $matches);
		$argstr = $this->args[$k];
		preg_match_all('/\((\w+)\)/', $argstr, $matches,PREG_SET_ORDER);
		if(count($matches)==count($vars)){
		foreach ($vars as $key=>$val){
		$argstr = preg_replace('/\('.$key.'\)/i', $val, $argstr);
		}
		return $base_url.str_replace(array('&','='), array('/','/'), stripcslashes($argstr)).config_item('url_suffix');
		}elseif(count($matches)>count($vars)){
		foreach ($vars as $key=>$val){
		$argstr = preg_replace('/\('.$key.'\)/i', $val, $argstr);
		}
		$argstr = preg_replace('/\/\((\w+)\)/', '', $argstr);
		return $base_url.stripcslashes($argstr).config_item('url_suffix');
		}
		}else if(!isset($uris[1]) AND ($k=='default_module')){
		return $base_url;
		}else if(!isset($uris[1]) AND !isset($this->args[$k])){
		return $base_url.stripcslashes($k).config_item('url_suffix');
		}else if(!isset($uris[1]) AND isset($this->args[$k])){
		return $base_url.stripcslashes($uris[0]).config_item('url_suffix');
		}
		} */
		if(isset($uris[1])){
			return $base_url.stripcslashes($uris[0]).'/'.str_replace(array('&','='), array('/','/'), stripcslashes($uris[1])).config_item('url_suffix');
		}else{
			return $base_url.stripcslashes($uris[0]).config_item('url_suffix');
		}
	}

	function _check_route_reg($uri){
		foreach ($this->routes as $key => $rule) {
			$newrule = str_replace(array(':any',':num','?'),array('[^&/]+','[0-9]+','\?'),$rule);
			$newrule = "#^$newrule$#";
			if(preg_match($newrule, $uri, $matches)){
				return $key;
			}
		}
		return false;
	}

	/**
	 *  Parse Routes
	 *
	 * This function matches any routes that may exist in
	 * the config/routes.php file against the URI to
	 * determine if the class/method need to be remapped.
	 *
	 * @access	private
	 * @return	void
	 */
	function _parse_routes(){
		// Turn the segment array into a URI string
		$uri = implode('/', $this->uri->segments);

		// Is there a literal match?  If so we're done
		if (isset($this->routes[$uri])){
			return $this->_set_request(explode('/', $this->routes[$uri]));
		}

		if(!in_array($uri, $this->skips)){

			// Loop through the route array looking for wild-cards
			foreach ($this->routes as $k => $val){
				// Convert wild-cards to RegEx
				$key = str_replace(':any', '[^&/]+', str_replace(':num', '[0-9]+', $k));

				// Does the RegEx match?
				if (preg_match('#^'.$key.'$#', $uri, $matches)){
					// Do we have a back-reference?
					if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE){
						$val = preg_replace('#^'.$key.'$#', $val, $uri);
					}

					if(isset($this->args[$k])){
						preg_match_all('/\((\w+)\)/', $this->args[$k], $args,PREG_SET_ORDER);
						for($i=1;$i<count($matches);$i++){
							$_GET[$args[$i-1][1]]=$matches[$i];
						}
					}

					return $this->_set_request(explode('/', $val));
				}
			}
		}
		if(($segsize = count($this->uri->segments))>2)
			for($u = 2; $u < $segsize; $u++){
			$_GET[$this->uri->segments[$u]]=$this->uri->segments[$u+1];$u+=1;
		}

		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_set_request($this->uri->segments);
	}

	// --------------------------------------------------------------------

	/**
	 * Set the class name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_class($class){
		$this->class = str_replace(array('/', '.'), '', $class).'_controller';
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch the current class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_class(){
		return $this->class;
	}

	// --------------------------------------------------------------------

	/**
	 *  Set the method name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_method($method){
		$this->method = $method;
	}

	// --------------------------------------------------------------------

	/**
	 *  Fetch the current method
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_method(){
		if ($this->method == $this->fetch_class()){
			return 'index';
		}

		return $this->method;
	}

	// --------------------------------------------------------------------

	/**
	 *  Set the directory name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_directory($dir){
		$this->directory = str_replace(array('/', '.'), '', $dir).'/';
	}

	// --------------------------------------------------------------------

	/**
	 *  Fetch the sub-directory (if any) that contains the requested controller class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_directory(){
		return $this->directory;
	}

	// --------------------------------------------------------------------

	/**
	 *  Set the controller overrides
	 *
	 * @access	public
	 * @param	array
	 * @return	null
	 */
	function _set_overrides($routing){
		if ( ! is_array($routing)){
			return;
		}

		if (isset($routing['module'])){
			$this->set_directory($routing['module']);
			$this->set_class($routing['module']);
		}

		if (isset($routing['function'])){
			$routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function'];
			$this->set_method($routing['function']);
		}
	}

}
